import React, { PureComponent } from 'react';
import { Spin } from 'antd';

import createScript from './createScript';
import { Conf } from '../../utils';

class Ueditor extends PureComponent{
    constructor(props){
        super(props);
        this.state = {
            loading:false,
            editor:{},
            id:this.props.id?this.props.id:'',
        }
    }
    loadUE() {
        const url = `/js/plugins/ueditor/ueditor.all.js`;
        const configUrl = `/js/plugins/ueditor/ueditor.config.js`;
        const langUrl = `/js/plugins/ueditor/lang/zh-cn/zh-cn.js`;
    
        /*
            ::this.initUE
            等同于
            this.initUE.bind(this)
        */
        // 顺序很重要~
        createScript(configUrl, () => {
            createScript(url, () => {
                createScript(langUrl, this.initUE);
            });
        });
    }

    initXiuMi(baseURL) {
        let UE = window.UE;
        UE.registerUI('dialog', (editor, uiName) => {
            return new UE.ui.Button({
                name: 'xiumi-connect',
                title: '秀米',
                onclick() {
                    const dialog = new UE.ui.Dialog({
                        iframeUrl: `${baseURL}xiumi-ue-dialog-v5.html`,
                        editor,
                        name: 'xiumi-connect',
                        title: '秀米图文消息助手',
                        cssRules: `width: ${window.innerWidth - 60}px;height: ${window.innerHeight - 60}px;`,
                    });

                    dialog.render();
                    dialog.open();
                },
            });
        });
    }


    initUE = ()=>{
        const baseURL = `/js/plugins/ueditor/`;
        let {id} = this.state;
        let {config,handleChange} = this.props;
        let UE = window.UE;
        let editor = {};

        if (config.hasOwnProperty('xiumi') && config.xiumi === true) {
            this.initXiuMi(baseURL);
        }

        if(id){
            try {
                UE.delEditor(id);
            } catch (e) {}
            const ue = editor = UE.getEditor(id, {
                UEDITOR_HOME_URL: baseURL,
                serverUrl: Conf.ajaxUrl +'ueditor',
                //serverUrl:Conf.fileUrl+'/api/ueditor/controll',
                initialFrameWidth: config.hasOwnProperty('width')?config.width:this.props.width,
                initialFrameHeight: config.hasOwnProperty('height')?config.height:this.props.height,
                autoHeightEnabled: config.hasOwnProperty('autoHeight')?config.autoHeight:this.props.autoHeight,
                zIndex: this.props.inModal ? 1001 : 999,
                autoFloatEnabled: !this.props.inModal,
                removeFormatAttributes: 'lang, align, hspace, valign',
                toolbars: config.hasOwnProperty('toolbars') && config.toolbars==='mini'?[
                    [
                        'fullscreen', 'source', '|',
                        'fontfamily', 'fontsize', 'bold', 'italic', 'underline', '|',
                        'forecolor', 'backcolor', '|',
                        'insertorderedlist', 'insertunorderedlist', '|',
                        'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
                        'horizontal', 'lineheight', '|',
                        'link', 'unlink', 'insertimage', 'attachment', '|',
                    ],
                ]:this.props.toolbars,
                allowDivTransToP: false,
            });
        
            ue.ready(() => {
                if (this.props.content) {
                    ue.setContent(this.props.content);
                }

                this.setState({
                    loading: false,
                    editor,
                });
            });

            //事件selectionChange 
            ue.addListener("contentChange",function(){
                handleChange(ue.getContent());
            });
            ue.addListener("blur",function(){
                handleChange(ue.getContent());
            });
            
        }
    }

    componentDidMount() {
        if (!window.baidu || !window.baidu.editor) {
            this.loadUE();
            this.setState({ loading: true });
        } else {
            this.initUE();
        }
    }
    componentWillUnmount() {
        let editor = this.state.editor;
        // 一定要写这一句
        editor.destroy();
    }
    render() {
        let id = this.props.id;
        let loading = this.state.loading;
        return (
            <Spin spinning={loading}>
                <script id={id} name={id} type="text/plain" />
            </Spin>
        );
    }
}
Ueditor.defaultProps = {
    id: '',
    width: '100%',
    height: '400',
    autoHeight: false,
    //withXiumi: false,
    inModal: false,
    toolbars:[
        [
            'source', //源代码
            '|',
            'undo', //撤销
            'redo', //重做
            '|',
            'bold', //加粗
            'forecolor', //字体颜色
            'backcolor', //背景色
            'italic', //斜体
            'underline', //下划线
            'strikethrough', //删除线
            'horizontal', //分隔线
            '|',
            'fontfamily', //字体
            'fontsize', //字号
        ],[
            //'paragraph', //段落格式
            'justifyleft', //居左对齐
            'justifyright', //居右对齐
            'justifycenter', //居中对齐
            'justifyjustify', //两端对齐
            'indent', //首行缩进
            'rowspacingtop', //段前距
            'rowspacingbottom', //段后距
            'insertframe', //插入Iframe
            'imagenone', //默认
            'imageleft', //左浮动
            'imageright', //右浮动
            'imagecenter', //居中
            'insertorderedlist', //有序列表
            'insertunorderedlist', //无序列表
            'lineheight', //行间距
            'edittip ', //编辑提示
            'autotypeset', //自动排版
            'link', //超链接
            'unlink', //取消链接
            'formatmatch', //格式刷
            'removeformat', //清除格式
            'cleardoc', //清空文档
            '|',
            //'simpleupload', //单图上传
            'insertimage', //多图上传
            'attachment', //附件
            'insertvideo', //视频
            'map', //Baidu地图
            'fullscreen', //全屏
            'wordimage', //图片转存
            '|',
            'inserttable', //插入表格
            'edittable', //表格属性
            'edittd', //单元格属性
            'insertrow', //前插入行
            'insertcol', //前插入列
            'insertparagraphbeforetable', //"表格前插入行"
            'mergeright', //右合并单元格
            'mergedown', //下合并单元格
            'deleterow', //删除行
            'deletecol', //删除列
            'splittorows', //拆分成行
            'splittocols', //拆分成列
            'splittocells', //完全拆分单元格
            'deletecaption', //删除表格标题
            'inserttitle', //插入标题
            'mergecells', //合并多个单元格
            'deletetable', //删除表格
            '|',
            'background', //背景
            'subscript', //下标
            'fontborder', //字符边框
            'superscript', //上标
            'spechars', //特殊字符
            'preview', //预览
        ]
    ]
};
export default Ueditor;